package YouBeiStorage

import (
	"strconv"
	"time"
	"youbei/dao"
	conf "youbei/utils/config"

	"github.com/gin-gonic/gin"
)

type ResAPI struct {
	Success int         `json:"success"`
	Msg     string      `json:"msg"`
	Result  interface{} `json:"result"`
}

func APIReturn(c *gin.Context, Success int, Msg string, data interface{}) {
	res := gin.H{
		"success": Success,
		"msg":     Msg,
		"result":  data,
	}
	c.AbortWithStatusJSON(Success, res)
}

// ClientApiStepOne 处理API第一步的请求
func ClientApiStepOne(c *gin.Context) {

	// 初始化响应的数据
	response := gin.H{}

	// 从文件中加载配置
	config, configError := conf.LoadConfigFromFile()
	// 如果加载配置出错，返回错误信息
	if configError != nil {
		response["status"] = 500
		response["msg"] = configError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 绑定请求数据
	request := dao.YSRequest{}
	if bindError := c.Bind(&request); bindError != nil {
		response["status"] = 500
		response["msg"] = bindError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}

	port, porterr := strconv.Atoi(request.Msg)
	if porterr != nil {
		response["status"] = 500
		response["msg"] = porterr.Error()
		c.AbortWithStatusJSON(500, response)
		return
	} else {
		if c.ClientIP() == "" {
			response["status"] = 500
			response["msg"] = "服务端ip获取为空"
			c.AbortWithStatusJSON(500, response)
			return
		}
	}

	// 从数据库中查找白名单
	whitelists := []dao.YSWhitelist{}
	if findError := dao.Localdb().Find(&whitelists); findError != nil {
		response["status"] = 500
		response["msg"] = findError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 如果白名单的长度大于等于1，返回错误信息
	if len(whitelists) >= 1 {
		response["status"] = 500
		response["msg"] = "len(whitelists) >= 1"
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 插入新的白名单
	whitelist := dao.YSWhitelist{
		ServerUuid: request.Uuid,
		ServerPort: port,
		ServerIP:   c.ClientIP(),
		Created:    time.Now().Unix(),
	}
	if _, insertError := dao.Localdb().Insert(&whitelist); insertError != nil {
		response["status"] = 500
		response["msg"] = insertError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 返回成功的响应
	response["status"] = 200
	response["msg"] = config.ConfClient.Uuid
	c.JSON(200, response)
}

// ClientApiStepTwo 处理API第二步的请求
func ClientApiStepTwo(c *gin.Context) {
	// 初始化响应数据
	response := gin.H{}

	// 绑定请求数据
	request := dao.Request{}
	if bindError := c.Bind(&request); bindError != nil {
		response["status"] = 500
		response["msg"] = bindError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 从数据库中查找对应的白名单
	whitelist := dao.YSWhitelist{}
	has, getError := dao.Localdb().Where("serveruuid=?", request.Uuid).Get(&whitelist)
	if getError != nil {
		response["status"] = 500
		response["msg"] = getError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}
	if !has {
		response["status"] = 500
		response["msg"] = "whitelist not found"
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 设置白名单的token
	whitelist.Token = request.Msg

	// 设置更新数据库
	if _, updateError := dao.Localdb().Where("serveruuid=?", request.Uuid).Cols("token").Update(&whitelist); updateError != nil {
		response["status"] = 500
		response["msg"] = updateError.Error()
		c.AbortWithStatusJSON(500, response)
		return
	}

	// 返回成功的响应
	response["status"] = 200
	response["msg"] = "ok"
	c.JSON(200, response)
}
